package com.lagou.factory;

import com.lagou.util.TXManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {

    @Autowired
    private TXManager transactionManager;

    /**
     * Jdk动态代理
     *
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getJdkProxy(Object obj) {

        // 获取代理对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object obj = null;
                        try {
                            System.out.println("开始事务");
                            transactionManager.startTransaction();
                            obj = method.invoke(obj, args);
                            System.out.println("提交事务");
                            transactionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("回滚事务");
                            transactionManager.rollback();
                            // 抛出异常便于上层servlet捕获
                            throw e;
                        } finally {
                            System.out.println("关闭事务");
                            transactionManager.release();
                        }
                        return obj;
                    }
                });

    }
}
